<template>
	<view class="container">
		<!-- 滚动区域 -->
		<view class="scroll-panel" v-show="goodShow">
			<view class="list-box">
				<view class="left">
					<scroll-view scroll-y="true" :style="{ 'height':scrollHeight }" :scroll-into-view="leftIntoView"
						:scroll-with-animation="true">
						<view class="item" v-for="(item,index) in leftArray" :key="index"
							:class="{ 'active':index==leftIndex }" :id="'left-'+index" :data-index="index"
							@tap="leftTap">{{item}}</view>
					</scroll-view>
				</view>
				<view class="main">
					<swiper class="swiper" :style="{ 'height':scrollHeight }" :current="leftIndex"
						@change="swiperChange" vertical="true">
						<swiper-item v-for="(item,index) in mainArray" :key="index">
							<scroll-view scroll-y="true" :style="{ 'height':scrollHeight }">
								<view class="item">
									<view class="title">
									</view>
									<view class="goodTable" v-for="(item2,index2) in item.list" :key="index2">
										<uni-row class="demo-uni-row">
											<uni-col :span="8">
												<view class="demo-uni-col dark">
													<image :src="item2.introduceImage" class="image_wrapper"
														mode="aspectFit"></image>
												</view>
											</uni-col>
											<uni-col :span="10">
												<view class="demo-uni-col light">
													<span style="color: #007AFF;">{{item2.name}}</span>
													<view class="describe">数量：<span>{{item2.quantity}}</span></view>
													<view class="describe">单位：<span>{{item2.unit}}</span></view>
													<view class="money">价格：{{item2.price}}元</view>
												</view>
											</uni-col>
											<uni-col :span="6">
												<view class="demo-uni-col light">
													<button style="height: 85rpx;width: 100rpx;" type="primary"
														@click="subtractNumber(item2)">-</button>
													<button style="height: 85rpx;width: 100rpx;" type="primary"
														@click="addNumber(item2)">+</button>
												</view>
											</uni-col>
										</uni-row>
									</view>
								</view>
							</scroll-view>
						</swiper-item>
					</swiper>
				</view>
			</view>
		</view>
		<!-- 购物车 -->
		<view style="width: 100%;height: 100%;" v-show="shopShow">
			<shopsComponent :goodsList="shopGoods" @subtractNumber="subtractNumber($event)"></shopsComponent>
		</view>
		<!-- 订单列表 -->
		<view style="width: 100%;height: 100%;" v-show="orderListShow">
			<orderList @getOrderList="getOrderList" :orderListParent="orderListParent" :orderShow="orderShow">
			</orderList>
		</view>
		<!-- 底部面板 -->
		<view class="cu-bar bg-white tabbar border shop">
			<view :class="goodShow?barClassShow:barClass" @click="showGoods()">
				<view class="cuIcon-similar"></view> 商品
			</view>
			<view :class="shopShow?barClassShow:barClass" @click="showShops()">
				<view class="cuIcon-cart">
					<view class="cu-tag badge"></view>
				</view>
				购物车
			</view>
			<view :class="orderListShow?barClassShow:barClass" @click="showOrderList()">
				<view class="cuIcon-similar"></view> 订单列表
			</view>
			<view class="bg-red submit" @tap="showModal" data-target="DialogModal2">立即订购</view>
		</view>
		<view class="cu-modal" :class="modalName=='DialogModal2'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">预订单确认</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-xl">
					<view class="cu-form-group">
						<view class="title">期望送达日期</view>
						<picker mode="date" :value="nowDate" :start="DataStart" :end="DataEnd" @change="DateChange">
							<view class="picker">
								{{nowDate}}
							</view>
						</picker>
					</view>
					<view class="cu-form-group">
						<view class="title">期望送达时间</view>
						<picker mode="time" :value="time" start="00:00" end="24:00" @change="TimeChange">
							<view class="picker">
								{{time}}
							</view>
						</picker>
					</view>
					<view class="cu-form-group align-start">
						<view class="title">预订单备注</view>
						<textarea maxlength="-1" @input="textareaBInput" placeholder="备注"></textarea>
					</view>
				</view>
				<view class="cu-bar bg-white">
					<view class="action margin-0 flex-sub text-green solid-left" @tap="hideModal">取消</view>
					<view class="action margin-0 flex-sub  solid-left" @tap="orderOk">确定</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import shopsComponent from '../shops/shops'
	import orderList from '../orderList/orderList'
	export default {
		data() {
			return {
				// 底部导航栏选中样式
				barClassShow: 'action text-orange',
				barClass: 'action text-gray',
				goodShow: true,
				shopShow: false,
				orderListShow: false,
				scrollHeight: '400px',
				leftArray: [],
				mainArray: [],
				leftIndex: 0,
				goodsType: [],
				goodList: [],
				// 购物车列表
				shopGoods: [],
				// 模态框
				modalName: '',
				// 日期开始时间-结束时间
				DataStart: '',
				DataEnd: '',
				// 时间日期
				time: '12:00',
				nowDate: '',
				// 多行文本域
				textareaBValue: '',
				// 订单列表
				orderListParent: [],
				// 订单列表显示状态
				orderShow: true

			}
		},
		components: {
			shopsComponent,
			orderList
		},
		computed: {
			/* 计算左侧滚动位置定位 */
			leftIntoView() {
				return `left-${this.leftIndex > 5 ? (this.leftIndex-5):0}`;
			}
		},
		beforeMount() {
			var now = new Date();
			var year = now.getFullYear(); //得到年份
			var month = now.getMonth(); //得到月份
			var day = now.getDate(); //得到天
			this.DataStart = year + '-' + (month + 1) + '-' + day;
			this.DataEnd = year + 2 + '-' + '12' + '-' + 31;
			this.nowDate = this.DataStart
		},
		mounted() {
			/* 等待DOM挂载完成 */
			this.$nextTick(() => {
				/* 在非H5平台，nextTick回调后有概率获取到错误的元素高度，则添加200ms的延迟来减少BUG的产生 */
			})
			/* 等待滚动区域初始化完成 */
			this.initScrollView().then(() => {
				/* 获取列表数据，你的代码从此处开始 */
				this.getListData();
			})
		},
		methods: {
			// 查询订单历史
			getOrderList() {
				uni.request({
					url: this.$serverApi + "/applet/order/pageOrder",
					method: "POST",
					data: JSON.stringify({
						"pageSize": 999,
						"currPage": 1
					}),
					header: {
						//返回数据类型
						"content-type": " application/json; charset=utf-8",
						//设置用户访问的token信息
						"Authorization": uni.getStorageSync("token")
					},
					success: res => {
						if (res.data.code == 200) {
							this.orderListParent = res.data.data.records
						} else {
							uni.showToast({
								title: '网络开小差咯!提交订单失败!',
								icon: 'none',
								duration: 2000
							});
						}
					},
					fail: res => {
						uni.showToast({
							title: '网络开小差咯!提交订单失败!',
							icon: 'none',
							duration: 2000
						});
					}
				})
			},
			// 确认订单
			orderOk() {
				var deliveryTime = this.nowDate + " " + this.time + ":00";
				var orderDetail = {
					"deliveryTime": deliveryTime,
					"remark": this.textareaBValue,
					"orderDetailFormList": this.shopGoods
				}
				uni.request({
					url: this.$serverApi + "/applet/order/addOrder",
					method: "POST",
					data: JSON.stringify(orderDetail),
					header: {
						//返回数据类型
						"content-type": " application/json; charset=utf-8",
						//设置用户访问的token信息
						"Authorization": uni.getStorageSync("token")
					},
					success: res => {
						if (res.data.code == 200) {
							uni.showToast({
								title: '提交订单成功',
								duration: 1000
							});
							this.modalName = null
							// 清空购物车
							this.shopGoods = []
						} else {
							uni.showToast({
								title: '网络开小差咯!提交订单失败!',
								icon: 'none',
								duration: 2000
							});
						}
					},
					fail: res => {
						uni.showToast({
							title: '网络开小差咯!提交订单失败!',
							icon: 'none',
							duration: 2000
						});
					}
				})
			},
			// 多行文本域
			textareaBInput(e) {
				this.textareaBValue = e.detail.value
			},
			// 时间日期选择
			TimeChange(e) {
				this.time = e.detail.value
			},
			DateChange(e) {
				this.nowDate = e.detail.value
			},
			// 显示模态框
			showModal(e) {
				if (this.shopGoods.length <= 0) {
					uni.showToast({
						title: '请选择商品！',
						icon: 'none',
						duration: 2000
					});
					return false;
				} else {
					this.modalName = e.currentTarget.dataset.target
				}
			},
			// 隐藏模态框
			hideModal(e) {
				this.modalName = null
			},
			// 添加商品数量
			addNumber(good) {
				good.quantity++
				let addFlag = true
				this.shopGoods.forEach(item => {
					// 如果id存在了就不添加 否则都添加
					if (item.id == good.id) {
						addFlag = false
					}
				})
				if (addFlag) {
					this.shopGoods.push(good)
				}
			},
			// 减少商品数量
			subtractNumber(good) {
				if (good.quantity >= 1) {
					if (--good.quantity == 0) {
						this.shopGoods.forEach((item, index) => {
							// 如果id存在了就不添加 否则都添加
							if (item.id == good.id) {
								this.shopGoods.splice(index, 1)
							}
						})
					}
				}
			},
			//展示商品列表 
			showGoods() {
				this.goodShow = true;
				this.shopShow = false;
				this.orderListShow = false;
			},
			// 展示购物车列表
			showShops() {
				this.goodShow = false;
				this.shopShow = true;
				this.orderListShow = false;
			},
			// 展示订单列表
			showOrderList() {
				this.orderListShow = true;
				this.goodShow = false;
				this.shopShow = false;
				this.getOrderList();
			},
			/* 初始化滚动区域 */
			initScrollView() {
				return new Promise((resolve, reject) => {
					let view = uni.createSelectorQuery().select('.scroll-panel');
					view.boundingClientRect(res => {
						this.scrollHeight = `${res.height}px`;
						this.$nextTick(() => {
							resolve();
						})
					}).exec();
				});
			},
			/* 获取列表数据 */
			getListData() {
				this.getTypes();
				new Promise((resolve, reject) => {
					uni.showLoading();
					setTimeout(() => {
						let [left, main] = [
							[],
							[]
						];
						for (let i = 0; i < this.goodsType.length; i++) {
							left.push(this.goodsType[i].value);
							let list = [];
							this.getgoodsByType(this.goodsType[i].id, function(res) {
								for (let j = 0; j < res.length; j++) {
									list.push(res[j]);
								}
							})
							main.push({
								title: `第${i+1}类商品标题`,
								list
							})
						}
						resolve({
							left,
							main
						});
					}, 1000);
				}).then((res) => {
					uni.hideLoading();
					this.leftArray = res.left;
					this.mainArray = res.main;
				});
			},
			/* 左侧导航点击 */
			leftTap(e) {
				let index = e.currentTarget.dataset.index;
				this.leftIndex = Number(index);
			},
			// 根据商品大类id获取商品
			async getgoodsByType(typeId, fn) {
				const that = this
				await uni.request({
					url: that.$serverApi + "/applet/commodity/listCommodity?typeId=" + typeId,
					method: "GET",
					header: {
						//返回数据类型
						"content-type": " application/json; charset=utf-8",
						//设置用户访问的token信息
						"Authorization": uni.getStorageSync("token")
					},
					success: res => {
						if (res.data.code == 200) {
							if (fn) {
								fn(res.data.data)
							}
						} else {}
					},
					fail: res => {}
				})
			},
			// 获取商品大类
			async getTypes() {
				await uni.request({
					url: this.$serverApi + "/applet/type/listAllType",
					method: "GET",
					data: {},
					header: {
						//返回数据类型
						"content-type": " application/json; charset=utf-8",
						//设置用户访问的token信息
						"Authorization": uni.getStorageSync("token")
					},
					success: res => {
						if (res.data.code == 200) {
							this.goodsType = res.data.data
						} else {}
					},
					fail: res => {}
				})
			},
			/* 轮播图切换 */
			swiperChange(e) {
				let index = e.detail.current;
				this.leftIndex = Number(index);
			}
		}
	}
</script>

<style lang="scss">
	page,
	.container {
		height: 100%;
	}

	.goodTable {
		margin-bottom: 30rpx;
	}

	/* 容器 */
	.container {
		display: flex;
		flex-direction: column;
		flex-wrap: nowrap;
		justify-content: flex-start;
		align-items: flex-start;
		align-content: flex-start;

		&>view {
			width: 100%;
		}

		.scroll-panel {
			flex-grow: 1;
			height: 0;
			overflow: hidden;
		}

		.bottom-panel {
			padding-bottom: 0;
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);
		}
	}

	.image_wrapper {
		width: 150rpx;
		height: 150rpx;
		margin: 0 auto;

		.img {
			width: 100%;
			height: 100%;
		}
	}

	.list-box {
		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
		justify-content: flex-start;
		align-items: flex-start;
		align-content: flex-start;
		font-size: 28rpx;

		.left {
			width: 200rpx;
			background-color: #f6f6f6;
			line-height: 80rpx;
			box-sizing: border-box;
			font-size: 32rpx;

			.item {
				padding-left: 20rpx;
				position: relative;

				&:not(:first-child) {
					margin-top: 1px;

					&::after {
						content: '';
						display: block;
						height: 0;
						border-top: #d6d6d6 solid 1px;
						width: 620upx;
						position: absolute;
						top: -1px;
						right: 0;
						transform: scaleY(0.5);
						/* 1px像素 */
					}
				}

				&.active,
				&:active {
					color: #42b983;
					background-color: #fff;
				}
			}
		}

		.main {
			background-color: #fff;
			padding-left: 20rpx;
			width: 0;
			flex-grow: 1;
			box-sizing: border-box;

			.swiper {
				height: 500px;
			}

			.title {
				line-height: 64rpx;
				font-size: 24rpx;
				font-weight: bold;
				color: #666;
				background-color: #fff;
				position: sticky;
				top: 0;
				z-index: 999;
			}

			.item {
				padding-bottom: 10rpx;
			}

			.this.goods {
				display: flex;
				flex-direction: row;
				flex-wrap: nowrap;
				justify-content: flex-start;
				align-items: center;
				align-content: center;
				margin-bottom: 10rpx;

				&>image {
					width: 120rpx;
					height: 120rpx;
					margin-right: 16rpx;
					margin-left: 2px;
				}

				.describe {
					font-size: 24rpx;
					color: #999;
				}

				.money {
					font-size: 24rpx;
					color: #efba21;
				}
			}
		}
	}

	// 模态框
	.cu-modal {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		z-index: 99;
		opacity: 0;
		outline: 0;
		text-align: center;
		-ms-transform: scale(1.185);
		transform: scale(1.185);
		backface-visibility: hidden;
		perspective: 2000upx;
		background: rgba(0, 0, 0, 0.6);
		transition: all 0.3s ease-in-out 0s;
		pointer-events: none;
	}

	.cu-modal::before {
		content: "\200B";
		display: inline-block;
		height: 100%;
		vertical-align: middle;
	}

	.cu-modal.show {
		opacity: 1;
		transition-duration: 0.3s;
		-ms-transform: scale(1);
		transform: scale(1);
		overflow-x: hidden;
		overflow-y: auto;
		pointer-events: auto;
	}

	.cu-dialog {
		position: relative;
		display: inline-block;
		vertical-align: middle;
		margin-left: auto;
		margin-right: auto;
		width: 680upx;
		max-width: 100%;
		background-color: #f8f8f8;
		border-radius: 10upx;
		overflow: hidden;
	}

	.cu-modal.bottom-modal::before {
		vertical-align: bottom;
	}

	.cu-modal.bottom-modal .cu-dialog {
		width: 100%;
		border-radius: 0;
	}

	.cu-modal.bottom-modal {
		margin-bottom: -1000upx;
	}

	.cu-modal.bottom-modal.show {
		margin-bottom: 0;
	}

	.cu-modal.drawer-modal {
		transform: scale(1);
		display: flex;
	}

	.cu-modal.drawer-modal .cu-dialog {
		height: 100%;
		min-width: 200upx;
		border-radius: 0;
		margin: initial;
		transition-duration: 0.3s;
	}

	.cu-modal.drawer-modal.justify-start .cu-dialog {
		transform: translateX(-100%);
	}

	.cu-modal.drawer-modal.justify-end .cu-dialog {
		transform: translateX(100%);
	}

	.cu-modal.drawer-modal.show .cu-dialog {
		transform: translateX(0%);
	}

	.cu-modal .cu-dialog>.cu-bar:first-child .action {
		min-width: 100rpx;
		margin-right: 0;
		min-height: 100rpx;
	}

	// 时间日期选择,文本框样式
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}

	.cu-form-group picker .picker {
		line-height: 100upx;
		font-size: 28upx;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
		width: 100%;
		text-align: right;
	}
</style>
